package com.ithinkstudio.jeez.config;

import com.ithinkstudio.jeez.async.AsyncExceptionHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;

/**
 * @description: 异常线程池配置
 * @author: fengzp
 * @create: 2020/04/21
 */
@Configuration
@EnableAsync
public class AsyncConfig implements AsyncConfigurer {

    @Value("${thread.core-pool-size: 10}")
    private int corePoolSize ;

    @Value("${thread.max-pool-size: 100}")
    private int maxPoolSize;

    @Value("${thread.queue-capacity: 100}")
    private int queueCapacity;

    @Value("${thread.wait-on-shutdown: true}")
    private boolean waitForTasksToCompleteOnShutdown;

    @Value("${thread.await-termination-seconds: 600}")
    private int awaitTerminationSeconds;

    @Value("${thread.prefix: AsyncThread}")
    private String prefix;

    @Override
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(corePoolSize);
        executor.setMaxPoolSize(maxPoolSize);
        executor.setQueueCapacity(queueCapacity);
        executor.setWaitForTasksToCompleteOnShutdown(waitForTasksToCompleteOnShutdown);
        executor.setAwaitTerminationSeconds(awaitTerminationSeconds);
        executor.setThreadNamePrefix(prefix);
        //如果不初始化，导致找到不到执行器
        executor.initialize();
        return executor;
    }

    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return new AsyncExceptionHandler();
    }


}
